<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use app\admin\controller\Cloudaccountwithdraw;
use OSS\OssClient;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FabangController extends Controller
{

    /**
     * 绑定审核列表
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['b.member_id','=',$param['member_id']];
        }
        if (isset($param['x_member_id']) && !empty($param['x_member_id'])) {
            $whehe[] = ['c.member_id','=',$param['member_id']];
        }
        if (isset($param['status']) && $param['status'] != '') {
            $whehe[] = ['a.status','=',$param['status']];
        }
        $whehetime = '';$start_time = 0;$end_time = 0;
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
        }
        $data = Db::table('fa_bang_info')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->join("fa_member c",'a.x_member_id = c.member_id','LEFT')
            ->where($whehe)
            ->where($whehetime)
            ->field('a.*,b.me_uid as s_me_uid,b.me_phone as s_me_phone,b.me_nick_name as s_me_nick_name,b.me_sex as s_me_sex,b.me_status as s_me_status,c.me_uid as x_me_uid,c.me_phone as x_me_phone,c.me_nick_name as x_me_nick_name,c.me_sex as x_me_sex,c.me_status as x_me_status')
            ->order('a.add_time desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $adminid = $this->uid;
        $data->each(function ($v, $k)use($adminid) {
            //只有超管能看全部手机号
            $v['s_zx'] = '';
            if(!empty(strpos($v['s_me_phone'], 'zx'))){
                $v['s_me_phone'] = explode('zx',$v['s_me_phone'])[0];
                $v['s_zx'] = '已注销';
            }
            $v['x_zx'] = '';
            if(!empty(strpos($v['x_me_phone'], 'zx'))){
                $v['x_me_phone'] = explode('zx',$v['x_me_phone'])[0];
                $v['x_zx'] = '已注销';
            }
            if($adminid != 1){
                $v['s_me_phone'] = hide_phone_number($v['s_me_phone']);
                $v['x_me_phone'] = hide_phone_number($v['x_me_phone']);
            }
            switch($v['s_me_sex']){
                case '0': $v['s_me_sex_word'] = '未设置';break;
                case '1': $v['s_me_sex_word'] = '男';break;
                case '2': $v['s_me_sex_word'] = '女';break;
            }
            switch($v['x_me_sex']){
                case '0': $v['x_me_sex_word'] = '未设置';break;
                case '1': $v['x_me_sex_word'] = '男';break;
                case '2': $v['x_me_sex_word'] = '女';break;
            }
            switch($v['s_me_status']){
                case '1': $v['s_me_status_word'] = '正常';break;
                case '2': $v['s_me_status_word'] = '已封禁';break;
            }
            switch($v['x_me_status']){
                case '1': $v['x_me_status_word'] = '正常';break;
                case '2': $v['x_me_status_word'] = '已封禁';break;
            }
            switch($v['status']){
                case '0': $v['status_word'] = '待处理';break;
                case '1': $v['status_word'] = '已同意';break;
                case '2': $v['status_word'] = '已拒绝';break;
            }
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['cl_time'] = !empty($v['cl_time'])?date('Y-m-d H:i:s',$v['cl_time']):'-';
            $v['img_url_arr'] = !empty($v['img_url'])?explode(',',$v['img_url']):[];
            $v['content_sl'] = cutStr($v['content'],5);
            $v['cl_content'] = !empty($v['cl_content'])?$v['cl_content']:'-';
            $v['cl_content_sl'] = cutStr($v['cl_content'],5);
            return $v;
        });

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }



    /**
     * 同意绑定 页面
     * User:@hang
     */
    public function passbang($id)
    {
        //查询申请详情
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_bang_info',"`id` = '{$id}'",'*');
        if(empty($info)){
            return admin_error('申请绑定信息未查询到',URL_CLOSE_REFRESH);
        }
        $is_show = '1';
        if($info['status'] != 0){
            $is_show = '这个绑定申请已经处理过，请关闭弹框，刷新页面再看！';
        }
        $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
        $this->assign([
            'data' => $id,
            'info' => $info,
            'is_show' => $is_show,
        ]);
        return $this->fetch();
    }

    /**
     * 确认 同意绑定
     * User:@hang
     */
    public function actionpassbang()
    {
        $content = replaceSpecialChar(input('content'));
        if(empty($content)){
            $content = '同意绑定下级申请';
        }
        $id = input('id');
        $IndexTableModel = New IndexTableModel();
        $tinfo = $IndexTableModel->getFind('fa_bang_info',"`id` = '{$id}'",'*');
        if(empty($tinfo)){
            return admin_error('申请信息未查询到',URL_CLOSE_REFRESH);
        }
        if($tinfo['status'] != 0){
            return admin_error('申请信息已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }

        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionpassbang'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }
        $xInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$tinfo['x_member_id']}'",'member_id,me_uid,me_bind_type,me_parent,me_nick_name,me_qd');
        if(empty($xInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('下级用户信息查询失败',URL_CLOSE_REFRESH);
        }
        if(!empty($xInfo['me_parent'])){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在上级用户，只能拒绝绑定申请',URL_CLOSE_REFRESH);
        }
        $inviteInfo = $IndexTableModel->getFind('fa_member_invite',"`b_member_id` = '{$xInfo['member_id']}'",'id');
        if(!empty($inviteInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在邀请日志',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();
        $res = $IndexTableModel->editInfo('fa_member',"`member_id` = '{$xInfo['member_id']}'",array('me_bind_type'=>1,'me_parent'=>$tinfo['member_id'],'me_bind_time'=>$ctime,'me_bind_admin'=>4));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改用户上级信息失败',URL_CLOSE_REFRESH);
        }

        $Common = New Common();
        $sjzdktjlry = $Common->getConfigValue('sjzdktjlry');//上级是此用户时自动打开奖励开关（多人用户ID#号拼接）
        if(!empty($sjzdktjlry)){
            $sjzdktjlryArr = explode('#',$sjzdktjlry);
            if(in_array($tinfo['member_id'],$sjzdktjlryArr)){
                $IndexTableModel->editInfo('fa_member',"`member_id` = '{$xInfo['member_id']}'",array('me_invitation_rewards'=>1,'me_czlwysp_rewards'=>1));
            }
        }

        $data = array();
        $data['member_id'] = $tinfo['member_id'];
        $data['b_member_id'] = $xInfo['member_id'];
        $data['me_bind_type'] = 1;
        $data['status'] = 1;
        $data['add_time'] = $ctime;
        $inviteRes = $IndexTableModel->addInfo('fa_member_invite',$data);
        if(empty($inviteRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('邀请日志添加失败',URL_CLOSE_REFRESH);
        }

        //为邀请者添加通知
        $inviteNewRes = $IndexTableModel->addInfo('fa_news_system',array('type'=>7,'member_id'=>$xInfo['member_id'],'j_member_id'=>$tinfo['member_id'],'g_table'=>'fa_member_invite','g_id'=>$inviteRes,'content'=>'恭喜您，用户【UID：'.$xInfo['me_uid'].'】昵称【'.$xInfo['me_nick_name'].'】，通过【申请绑定下级】(管理端操作)的方式，已经成为您的下级用户。','is_read'=>0,'add_time'=>$ctime));
        if(empty($inviteNewRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('为邀请者添加通知失败',URL_CLOSE_REFRESH);
        }

        $bangres = $IndexTableModel->editInfo('fa_bang_info',"`id` = '{$id}'",array('status'=>1,'cl_content'=>$content,'cl_time'=>$ctime));
        if(empty($bangres)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改信息状态失败',URL_CLOSE_REFRESH);
        }

        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 3;
        $data['member_id'] = $tinfo['member_id'];
        $data['d_member_id'] = $xInfo['member_id'];
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$tinfo['member_id']}'",'member_id,me_uid,me_bind_type,me_parent');
        $data['content'] = '为【'.$memberInfo['member_id'].'】绑定下级用户【'.$xInfo['member_id'].'】';
        $data['add_time'] = $ctime;
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('同意绑定成功，并且已经为申请者绑定下级用户', URL_CLOSE_REFRESH);
    }


    /**
     * 拒绝绑定 页面
     * User:@hang
     */
    public function refusebang($id)
    {
        ///查询申请详情
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_bang_info',"`id` = '{$id}'",'*');
        if(empty($info)){
            return admin_error('申请绑定信息未查询到',URL_CLOSE_REFRESH);
        }
        $is_show = '1';
        if($info['status'] != 0){
            $is_show = '这个绑定申请已经处理过，请关闭弹框，刷新页面再看！';
        }
        $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
        $this->assign([
            'data' => $id,
            'info' => $info,
            'is_show' => $is_show,
        ]);
        return $this->fetch();
    }



    /**
     * 确认 拒绝绑定
     * User:@hang
     */
    public function actionrefusebang()
    {
        $content = replaceSpecialChar(input('content'));
        if(empty($content)){
            $content = '拒绝绑定下级申请';
        }
        $id = input('id');
        $IndexTableModel = New IndexTableModel();
        $tinfo = $IndexTableModel->getFind('fa_bang_info',"`id` = '{$id}'",'*');
        if(empty($tinfo)){
            return admin_error('申请信息未查询到',URL_CLOSE_REFRESH);
        }
        if($tinfo['status'] != 0){
            return admin_error('申请信息已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }

        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionrefusebang'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }

        $ctime = time();
        Db::startTrans();
        $bangres = $IndexTableModel->editInfo('fa_bang_info',"`id` = '{$id}'",array('status'=>2,'cl_content'=>$content,'cl_time'=>$ctime));
        if(empty($bangres)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改信息状态失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('拒绝申请者的绑定下级成功', URL_CLOSE_REFRESH);
    }




}
